/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 *        1
 *      /   \
 *     2     3
 *    / \   / \
 *   4   5 6   7
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (tree, p, q) {
  console.log(tree)
  if (!tree || p === tree.val || q === tree.val) {
    return tree;
  }
  // 递归调用
  let left = lowestCommonAncestor(tree.left, p, q);
  let right = lowestCommonAncestor(tree.right, p, q);
  console.log('递归结果', left, right, tree);
  // 左树和右树都没有，返回根节点
  // if(!left && !right) {
  //   return tree;
  // }

  // return left === null ? right : right === null ? left : tree
  if(!left) {
    return right;
  }
  if(!right) {
    return left;
  }
  return tree;
};

var tree = {
  val: 1,
  left: {
    val: 2,
    left: {
      val: 4
    },
    right: {
      val: 5
    }
  },
  right: {
    val: 3,
    left: {
      val: 6
    },
    right: {
      val: 7
    }
  }
}

console.log(lowestCommonAncestor(tree, 7, 5));